/*
 * Copyright 2011 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package eu.vranckaert.calendar.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import eu.vranckaert.calendar.R;
import eu.vranckaert.calendar.util.UIUtils;

import java.util.Calendar;
import java.util.Date;

public class MonthCellView extends LinearLayout {
    private CellViewClickListener onClickListener;

    private Date mDate;
    private boolean mCurrentMonth;
    private int mRow;
    private int mColumn;
    private TextView countTextView;

    private int currentMonthBgColor = Color.LTGRAY;
    private int otherMonthBgColor = Color.GRAY;
    private int currentDayBgColor = Color.WHITE;

    public MonthCellView(Context context) {
        this(context, null);
    }

    public MonthCellView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MonthCellView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs);

        final TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.MonthCellView, defStyle, 0);

        currentMonthBgColor = a.getColor(R.styleable.MonthCellView_currentMonthBackgroundColor, currentMonthBgColor);
        otherMonthBgColor = a.getColor(R.styleable.MonthCellView_otherMonthBackgroundColor, otherMonthBgColor);
        currentDayBgColor = a.getColor(R.styleable.MonthCellView_currentDayBackgroundColor, currentDayBgColor);

        a.recycle();
    }

    public void init(Date date, boolean currentMonth, int row, int column, CellViewClickListener onClickListener) {
        this.mDate = date;
        this.mCurrentMonth = currentMonth;
        this.mRow = row;
        this.mColumn = column;
        this.onClickListener = onClickListener;
    }

    public int getRow() {
        return mRow;
    }

    public int getColumn() {
        return mColumn;
    }

    @SuppressLint("DrawAllocation")
	@SuppressWarnings("deprecation")
	@Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        if (mDate == null)
            return;

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(mDate);

        final int count = getChildCount();
        for (int i=0; i<count; i++) {
            View child = getChildAt(i);

            int height = 0;

            if (child instanceof TextView) {
                if (i == 0) { // The TextView for the current day of the month
                    TextView dayTextView = (TextView) child;
                    dayTextView.setText("" + calendar.get(Calendar.DAY_OF_MONTH));

                    final int top = 0;
                    final int bottom = top + dayTextView.getLineHeight();
                    final int left = 0;
                    final int right = getWidth();

                    height += bottom;

                    dayTextView.layout(left, top, right, bottom);

                    dayTextView.setGravity(Gravity.CENTER_HORIZONTAL);

                    int textColor = -1;
                    if (!mCurrentMonth) {
                        textColor = getContext().getResources().getColor(R.color.calendar_month_out_of_month_text);
                    } else {
                        textColor = getContext().getResources().getColor(R.color.calendar_month_this_month_text);

                        Calendar today = Calendar.getInstance();
                        if (today.get(Calendar.YEAR) == calendar.get(Calendar.YEAR)
                                && today.get(Calendar.MONTH) == calendar.get(Calendar.MONTH)
                                && today.get(Calendar.DAY_OF_MONTH) == calendar.get(Calendar.DAY_OF_MONTH)) {
                            dayTextView.setTypeface(null, Typeface.BOLD);
                        }
                    }
                    dayTextView.setTextColor(textColor);
                } else if (i == 1) { // The TextView for the number of items to be displayed
                    countTextView = (TextView) child;

                    final int top = ((getHeight() - height) - countTextView.getLineHeight()) / 2;
                    final int bottom = top + countTextView.getLineHeight();
                    final int left = 0;
                    final int right = getWidth();

                    height += bottom;

                    countTextView.layout(left, top, right, bottom);
                    countTextView.setGravity(Gravity.CENTER_HORIZONTAL);
                    countTextView.setVisibility(View.GONE);
                }
            }
        }

        int backgroundColor = -1;
        if (!mCurrentMonth) {
            backgroundColor = otherMonthBgColor;
        } else {
            Calendar today = Calendar.getInstance();
            if (today.get(Calendar.YEAR) == calendar.get(Calendar.YEAR)
                    && today.get(Calendar.MONTH) == calendar.get(Calendar.MONTH)
                    && today.get(Calendar.DAY_OF_MONTH) == calendar.get(Calendar.DAY_OF_MONTH)) {
                backgroundColor = currentDayBgColor;
            } else {
                backgroundColor = currentMonthBgColor;
            }
        }

        setClickable(true);

        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onClickListener != null) {
                    onClickListener.onClick(MonthCellView.this);
                }
            }
        });
        super.setBackgroundDrawable(UIUtils.createBackground(getContext(), backgroundColor));
    }

    public void removeCount() {
        if (countTextView != null) {
            countTextView.setText("" + 0);
            countTextView.setVisibility(View.GONE);
        }
    }

    public void addCount(int count) {
        if (countTextView != null) {
            countTextView.setText("" + count);
            countTextView.setVisibility(View.VISIBLE);
        }
    }

    /**
     * The on-click listener that will be triggered if a cell get's clicked/touched.
     */
    public interface CellViewClickListener {
        /**
         * Gets called automatically when a specific cell is clicked/touched.
         * @param monthCellView The {@link MonthCellView} that has been clicked/touched.
         * @return {@link Boolean#TRUE} if the click is handled, {@link Boolean#FALSE} if not.
         */
        boolean onClick(MonthCellView monthCellView);
    }

    public Date getDate() {
        return mDate;
    }
}
